package com.pengshun.modules.security;

import com.alibaba.fastjson.JSON;
import com.pengshun.modules.common.BaseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Author: liudongbo
 * @Date: 2019-11-04 18:03
 */
@Component
public class LoginSuccessHandle extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("jwtToken");
        HandlerMethod handlerMethod = null;
        //获取执行方法上的注解
        if(handler instanceof  HandlerMethod){
            handlerMethod = (HandlerMethod) handler;
        }else{
            return true;
        }

        Method method = handlerMethod.getMethod();
        Annotation[][] annotations = method.getParameterAnnotations();
        Boolean flag = false;
        if(annotations != null){
            for(Annotation[] annotation:annotations){
                if(annotation != null){
                    for(Annotation annotation1 : annotation){
                        if(annotation1 instanceof CurrUserInfo){
                            flag = true;
                        }
                    }
                }
            }
        }
        if(flag && StringUtils.isBlank(authHeader)){
            BaseResult result= new BaseResult(2,"token失效!");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
